package com.wnxy.portal.controller;

import cn.hutool.jwt.JWTUtil;
import com.wnxy.portal.anno.Idempotent;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.common.result.impl.BusinessCodeEnum;
import com.wnxy.portal.model.vo.CartVo;
import com.wnxy.portal.model.vo.OrderVo;
import com.wnxy.portal.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jet
 * @since 2023-12-11
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 生成订单
    @PostMapping("/submitOrder/{addressId}/{uniqueId}")
    // 幂等校验注解
    @Idempotent(expireTime = 20, timeUnit = TimeUnit.SECONDS)
    public Result submitOrder(
            @RequestBody CartVo cartVo,
            @RequestHeader("Authorization")String token,
            @PathVariable("addressId")Integer addressId,
            @PathVariable("uniqueId")String uniqueId){

        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        // 创建订单
        orderService.submitOrder(Long.parseLong(userId),addressId,cartVo);
        return Result.ok();
    }

    // 查询待支付订单: select * from t_order where state=1 and user_id=1
    @GetMapping("/waitPay")
    public Result queryWaitPay(@RequestHeader("Authorization")String token) {
        token = token.replace("Bearer ","");
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        List<OrderVo> orderVos = orderService.queryWaitPay(userId);
        return Result.ok(orderVos);
    }


    // 支付接口, 使用自定义幂等注解
    @PostMapping("/pay/{orderId}")
    @Idempotent(expireTime = 20, timeUnit = TimeUnit.SECONDS)
    public Result pay(
            @PathVariable("orderId")Long orderId,
            @RequestHeader("uniqueCode")String uniqueCode) {
        orderService.pay(orderId);
        return Result.ok();
    }
}












